package com.tanhua.manage.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.tanhua.manage.domain.Admin;
import com.tanhua.manage.exception.BusinessException;
import com.tanhua.manage.interceptor.AdminHolder;
import com.tanhua.manage.service.AdminService;
import com.tanhua.manage.vo.AdminVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/system/users")
public class AdminController {


    @Autowired
    private AdminService adminService;


    /**
     * 如果要下载或者直接输出一张图片，返回值是什么？ void
     * 接口名称：用户登录验证码图片
     * 接口路径：GET/system/users/verification
     */
    @GetMapping("/verification")
    public void verification(String uuid ,HttpServletResponse response) throws IOException {
        //1. 由于验证码是一张图片，浏览器对于图片很容易形参缓存，所以一定要通知浏览器别缓存该图片
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // 响应数据格式
        response.setContentType("image/jpeg");

        //2. 生成验证码
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(299,97);
        //3. 把生成验证码存储到redis中。
        String code = captcha.getCode();
        adminService.saveCap(uuid,"123456"); //redis.set( ,code)
        //4. 把验证码图片写出
        captcha.write(response.getOutputStream());

    }


    /**
     *接口名称：用户登录
     * 接口路径：POST /system/users/login
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody  Map<String,String> paramMap) throws  BusinessException {
        return adminService.login(paramMap);
    }


    /**
     *接口名称：用户基本信息
     * 接口路径：POST /system/users/profile
     */
    @PostMapping("/profile")
    public ResponseEntity profile()  {
        //1. 得到当前的登陆者
        Admin admin = AdminHolder.getAdmin();
        //2. 把Admin对象拷贝到adminVo对象
        AdminVo vo= new AdminVo();
        BeanUtils.copyProperties(admin,vo);
        return ResponseEntity.ok(vo);
    }


    /**
     *接口名称：用户登出
     *接口路径：POST/system/users/logout
     *
     */
    @PostMapping("/logout")
    public ResponseEntity logout(@RequestHeader("Authorization") String token)  {
        token = token.replace("Bearer ", "");
        return adminService.logout(token);
    }
}
